package com.hnevc.mallserver3.controller;

import com.hnevc.mallserver3.common.ResponseResult;
import com.hnevc.mallserver3.entity.Member;
import com.hnevc.mallserver3.service.MemberService;
import com.hnevc.mallserver3.service.impl.MemberServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.utility.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
@Api(tags = "用户会员信息接口")
public class MemberController {

    @Autowired

    private MemberServiceImpl memberService;

    @PostMapping("/login")
    @ApiOperation(value = "login", notes = "根据电话和密码登录")
    @ResponseBody
    public ResponseResult login(@RequestBody Member member) {
        System.out.println(member);
        Member member2 = memberService.login(member.getMemberPhone(), member.getPassword());
        if (member2 != null) {
            return ResponseResult.success(member2);
        } else {
            return ResponseResult.error(401, "登录失败，‌用户名或密码错误");
        }
    }

    @PostMapping("/login2")
    @ApiOperation(value = "login2", notes = "根据用户名和密码登录")

    public ResponseResult login2(@RequestBody Member member) {
        Member member2 = memberService.login2(member.getUsername(), member.getPassword());
        if (member2 != null) {
            return ResponseResult.success(member2);
        } else {
            return ResponseResult.error(401, "登录失败，‌用户名或密码错误");
        }
    }

    @PostMapping("/add")
    @ApiOperation(value = "addMember", notes = "添加会员")

    public ResponseResult addMember(@RequestBody Member member) {
        boolean result = memberService.save(member);
        if (result) {
            return ResponseResult.success("添加成功");
        } else {
            return ResponseResult.error(500, "添加失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "deleteMember", notes = "删除会员，根据ID")

    public ResponseResult deleteMember(@PathVariable Long id) {
        boolean result = memberService.removeById(id);
        if (result) {
            return ResponseResult.success("删除成功");
        } else {
            return ResponseResult.error(500, "删除失败");
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "getMemberById", notes = "获取会员信息，根据ID")

    public ResponseResult getMemberById(@PathVariable Long id) {
        Member member = memberService.getById(id);
        if (member != null) {
            return ResponseResult.success(member);
        } else {
            return ResponseResult.error(404, "会员不存在");
        }
    }

    @GetMapping("/list")
    @ApiOperation(value = "listMembers", notes = "获取会员列表")

    public ResponseResult listMembers() {
        List<Member> members = memberService.list();
        return ResponseResult.success(members);
    }

    @PutMapping("/update")
    @ApiOperation(value = "updateMember", notes = "更新会员信息")

    public ResponseResult updateMember(@RequestBody Member member) {
        boolean result = memberService.updateById(member);
        if (result) {
            return ResponseResult.success("更新成功");
        } else {
            return ResponseResult.error(500, "更新失败");
        }
    }

    @PostMapping("/upload_headpic")
    @ApiOperation(value = "更新用户头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file",value = "用户头像"),
            @ApiImplicitParam(name = "id",value = "用户ID")
    })
    public Map<String,Object> uploadHeadPic(@RequestParam("file") MultipartFile file,
                                            @RequestParam("id") Integer id){
        Map<String,Object> map = new HashMap<>();
        try {
            byte[] bytes = file.getBytes();
            String filePath =  new RandomString(10).nextString() + file.getOriginalFilename();
            Path path = Paths.get("D://upload//headpic//" +filePath);
            Files.write(path, bytes);
            map.put("success",true);
            map.put("msg","成功");
            //TODO 更新到数据库
            // 1. 获取用户服务对象，
            Member member = memberService.updateHeadPic(id, "/headpic/" + filePath);
            map.put("data",member);

        } catch (IOException e) {
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","文件读取错误");
        }
        return map;
    }
}
